package com.ywu.bpmn.form.service.service;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.bpmn.form.service.data.YwuFormDefinitionRepository;
import com.ywu.bpmn.form.service.data.YwuFormInstanceRepository;
import com.ywu.bpmn.form.service.dto.YwuFormDefinitionDto;
import com.ywu.bpmn.form.service.dto.YwuFormInstanceConditionDto;
import com.ywu.bpmn.form.service.dto.YwuFormInstanceDto;
import com.ywu.bpmn.form.service.entity.YwuFormDefinitionEntity;
import com.ywu.bpmn.form.service.entity.YwuFormInstanceConditionEntity;
import com.ywu.bpmn.form.service.entity.YwuFormInstanceEntity;
import com.ywu.common.entity.PageList;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName YwuFormInstanceService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/4/21 0:12
 * @Version 1.0
 **/
@Service
public class YwuFormInstanceService {
    @Autowired
    private YwuFormInstanceRepository repository;

    @Autowired
    private YwuFormDefinitionRepository definitionRepository;

    /**
    * @Author GroundDemo
    * @Description 校验权限，是否属于当前租户
    * @Date 0:35 2025/4/21
    * @Param [dto, isQueryJson]
    * @return com.ywu.bpmn.form.service.entity.YwuFormDefinitionEntity
    **/
    private YwuFormDefinitionEntity queryEntityByTenantId(YwuFormDefinitionDto dto, boolean isQueryJson) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        YwuFormDefinitionEntity queryRes;
        YwuFormDefinitionEntity search = new YwuFormDefinitionEntity();
        search.setId(dto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        if (isQueryJson) {
            queryRes = definitionRepository.getEntity(search);
        } else {
            queryRes = definitionRepository.getEntityNoJson(search);
        }
        if (Objects.isNull(queryRes)) {
            return null;
        } else {
            return queryRes;
        }
    }

    /**
    * @Author GroundDemo
    * @Description 添加表单实例
    * @Date 0:34 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> addFormInstance(YwuFormInstanceDto dto) {
        // 判断当前表单是否可操作
        YwuFormDefinitionDto definitionDto = new YwuFormDefinitionDto();
        definitionDto.setId(dto.getFormId());
        YwuFormDefinitionEntity definitionEntity = queryEntityByTenantId(definitionDto, false);
        if (Objects.isNull(definitionEntity)) {
            return CommonResult.error().setErrorCode("form.id.is.not.exist");
        }
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 构建插入数据
        YwuFormInstanceEntity insert = new YwuFormInstanceEntity();
        BeanUtils.copyProperties(dto, insert);
        insert.setId(TimerIdGenerateUtil.nextId());
        insert.createInfo(currentContext.getYwuContextUser().getUserAccount());
        insert.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        repository.insert(insert);
        return CommonResult.success(insert.getId());
    }

    /**
    * @Author GroundDemo
    * @Description 修改表单实例
    * @Date 0:39 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateFormInstance(YwuFormInstanceDto dto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 判断当前表单是否可操作
        YwuFormDefinitionDto definitionDto = new YwuFormDefinitionDto();
        definitionDto.setId(dto.getFormId());
        YwuFormDefinitionEntity definitionEntity = queryEntityByTenantId(definitionDto, false);
        if (Objects.isNull(definitionEntity)) {
            return CommonResult.error().setErrorCode("form.id.is.not.exist");
        }
        // 构建插入数据
        YwuFormInstanceEntity update = new YwuFormInstanceEntity();
        BeanUtils.copyProperties(dto, update);
        update.updateInfo(currentContext.getYwuContextUser().getUserAccount());
        repository.update(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除表单实例
    * @Date 0:41 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteFormInstance(YwuFormInstanceDto dto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 判断当前表单是否可操作
        YwuFormInstanceEntity search = new YwuFormInstanceEntity();
        search.setId(dto.getId());
        search.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        YwuFormInstanceEntity queryRes = repository.getEntity(search, new ArrayList<>());
        if (Objects.isNull(queryRes)) {
            return CommonResult.error().setErrorCode("form.instance.is.not.exist");
        }
        // 构建插入数据
        YwuFormInstanceEntity delete = new YwuFormInstanceEntity();
        delete.setId(dto.getId());
        repository.delete(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询表单实例数据
    * @Date 0:44 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryPageList(YwuFormInstanceDto dto) {
        // 构建参数
        PageService.execPageStartAndEnd(dto.getPageInfo());
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        dto.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        // 查询数量
        int count = repository.queryCount(dto, dto.getExtendFormFieldList());
        if (count == 0) {
            PageList<YwuFormInstanceEntity> pageList = new PageList<>(dto.getPageInfo().getPageIndex(),
                    dto.getPageInfo().getPageSize(), count, new ArrayList<>());
            return CommonResult.success(pageList);
        }
        // 分页查询数据
        List<YwuFormInstanceEntity> pageList = repository.queryPageList(dto, dto.getExtendFormFieldList());
        PageList<YwuFormInstanceEntity> page = new PageList<>(dto.getPageInfo().getPageIndex(),
                dto.getPageInfo().getPageSize(), count, pageList);
        return CommonResult.success(page);
    }

    /**
    * @Author GroundDemo
    * @Description 查询当前表单实例版本的动态查询条件
    * @Date 9:27 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> formInstanceConditionQuery(YwuFormInstanceConditionDto dto) {
        // 判断当前表单是否可操作
        YwuFormDefinitionDto definitionDto = new YwuFormDefinitionDto();
        definitionDto.setId(dto.getFormId());
        YwuFormDefinitionEntity definitionEntity = queryEntityByTenantId(definitionDto, false);
        if (Objects.isNull(definitionEntity)) {
            return CommonResult.error().setErrorCode("form.id.is.not.exist");
        }
        // 查询条件
        YwuFormInstanceConditionEntity searchEntity = new YwuFormInstanceConditionEntity();
        searchEntity.setFormId(dto.getFormId());
        searchEntity.setFormVersion(dto.getFormVersion());
        YwuFormInstanceConditionEntity conditionEntity = repository.getConditionEntity(searchEntity);
        return CommonResult.success(conditionEntity);
    }

    /**
    * @Author GroundDemo
    * @Description 添加表单实例下的所有表单动态条件
    * @Date 9:31 2025/4/21
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> formInstanceConditionInsert(YwuFormInstanceConditionDto dto) {
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        // 判断当前表单是否可操作
        YwuFormDefinitionDto definitionDto = new YwuFormDefinitionDto();
        definitionDto.setId(dto.getFormId());
        YwuFormDefinitionEntity definitionEntity = queryEntityByTenantId(definitionDto, false);
        if (Objects.isNull(definitionEntity)) {
            return CommonResult.error().setErrorCode("form.id.is.not.exist");
        }
        // 构建对象
        YwuFormInstanceConditionEntity insert = new YwuFormInstanceConditionEntity();
        insert.setId(TimerIdGenerateUtil.nextId());
        insert.setFormConditionJson(dto.getFormConditionJson());
        insert.setTenantId(currentContext.getYwuContextTenant().getTenantId());
        insert.setFormId(dto.getFormId());
        insert.setFormVersion(dto.getFormVersion());
        insert.createInfo(currentContext.getYwuContextUser().getUserAccount());
        // 先删除原始数据
        repository.deleteCondition(insert);
        repository.insertCondition(insert);
        return CommonResult.success(null);
    }
}
